﻿using AppTemplate.UI.Controls;
using AppTemplate.UI.Framework;
using AppTemplate.UI.Sys;
using AppTemplate.UI.Views;
using CommunityToolkit.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace AppTemplate.UI.ViewModels
{
    public partial class TabViewModel : ViewModel
    {

        private RelayCommand<object> OpenViewCommand { get; set; }
        public List<MenuItem> Menus { get; set; }

        public ObservableCollection<ClosableTabItem> Tabs { get; set; }

        [ObservableProperty]
        private ClosableTabItem currentTab;

        ContextMenu ContextMenu { get; set; }

        public TabViewModel()
        {
            InitMenu();
            InitContextMenu();
            InitTabs();

        }

        private void InitTabs()
        {
            Tabs = new();
            OpenTabByType(typeof(WelcomeView));
        }

        private void InitMenu()
        {
            var menus = CreateMenus()!;

            OpenViewCommand = new RelayCommand<object>(OpenTab);
            SetCommand(menus, OpenViewCommand);
            Menus = menus;

            var i = new MenuItem { Header = "界面转跳",Icon= CreateIcon("jiemian.png") };
            i.Click += (s, e) => { App.Go<OtherView>(); };
            Menus.Add(i);
        }

        private void InitContextMenu()
        {
            ContextMenu = new ContextMenu();
            ContextMenu.Items.Add(new MenuItem { Style = null, Header = "关闭本页", Command = CloseTabCommand });
            ContextMenu.Items.Add(new MenuItem { Style = null, Header = "关闭其他页", Command = CloseOtherTabCommand });
            ContextMenu.Items.Add(new MenuItem { Style = null, Header = "新开", Command = CloneTabCommand });
        }

        private void ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            ClosableTabItem tab = (ClosableTabItem)sender;
            var closeItem = (MenuItem)ContextMenu.Items[0];
            closeItem.IsEnabled = tab.Closable;
        }

        private void OpenTab(object? parameter)
        {
            Type? type = parameter as Type;
            if (parameter == null)
                return;
            OpenTabByType(type!);
        }

        private void OpenTabByType(Type viewType, bool? forceClone = false)
        {
            Guard.IsNotNull(viewType);

            var view = DI.Resolve(viewType);
            if (view == null)
                throw new InvalidOperationException("该视图未注册");

            TabPageAttribute? tabPageAttr = viewType.GetCustomAttribute<TabPageAttribute>();
            bool? allowMulti = tabPageAttr?.AllowMulti ?? false;
            if (!allowMulti.Value && (forceClone == null || forceClone.Value == false))
            {
                var existTab = Tabs.FirstOrDefault(t => t.Content != null && t.Content.GetType() == viewType);
                if (existTab != null)
                {
                    CurrentTab = existTab;
                    return;
                }
            }


            ViewAttribute? viewAttr = viewType.GetCustomAttribute<ViewAttribute>();
            FrameworkElement? fe = view as FrameworkElement;
            if (viewAttr != null && fe != null)
            {
                var viewModel = DI.Resolve(viewAttr.ViewModelType);
                fe.DataContext = viewModel;
            }



            string tabHeader = tabPageAttr?.Header ?? viewAttr?.Title ?? "未命名";
            bool closable = tabPageAttr?.Closable ?? true;

            var tab = new ClosableTabItem() { Closable = closable, Header = tabHeader, Content = view, IsSelected = true };
            tab.ContextMenu = ContextMenu;
            tab.ContextMenuOpening += ContextMenuOpening;
            tab.CloseTabHandler += CloseTab;
            Tabs.Add(tab);
        }

        private void CloseTab(ClosableTabItem tab)
        {
            if (tab.Closable)
            {
                Tabs.Remove(tab);
            }
        }

        [RelayCommand]
        private void CloneTab()
        {
            ClosableTabItem? tab = GetContextTarget();
            if (tab is not null)
            {
                var viewType = tab.Content.GetType();
                OpenTabByType(viewType, true);
            }
        }

        [RelayCommand]
        private void CloseTab()
        {
            ClosableTabItem? tab = GetContextTarget();
            if (tab is not null)
            {
                CloseTab(tab);
            }
        }

        private ClosableTabItem? GetContextTarget()
        {
            var target = ContextMenu.PlacementTarget;
            var tab = target as ClosableTabItem;
            return tab;
        }

        [RelayCommand]
        private void CloseOtherTab()
        {
            ClosableTabItem? tab = GetContextTarget();
            if (tab is not null)
            {
                var otherTabs = Tabs.Where(t => t != tab && t.Closable == true).ToList();
                if (otherTabs.Any())
                {
                    foreach (var ot in otherTabs)
                    {
                        Tabs.Remove(ot);
                    }
                }
            }
        }

        private void SetCommand(List<MenuItem> menus, RelayCommand<object> openViewCommand)
        {
            foreach (var m in menus)
            {
                SetCommand(m, openViewCommand);
            }
        }
        private void SetCommand(MenuItem menu, RelayCommand<object> openViewCommand)
        {
            if (menu.Items.Count > 0)
            {
                foreach (var m in menu.Items)
                {
                    SetCommand((MenuItem)m, openViewCommand);
                }
            }
            else
            {
                menu.Command = openViewCommand;
            }
        }


        public List<MenuItem> CreateMenus()
        {

            var functionItem = CreateMenuItem("功能演示", typeof(FunctionView), "gongneng.png");
            var userMenuItem = CreateMenuItem("数据列表", typeof(DataListView), "data.png");
            var iconFontItem = CreateMenuItem("IconFont", typeof(IconFontView), "iconfont.png");
            return new List<MenuItem> {

                functionItem,
                 userMenuItem,
                iconFontItem,
            };
        }

        private MenuItem CreateMenuItem(string header, Type viewType, string icon)
        {
            return new MenuItem { Icon = CreateIcon(icon), Header = header, CommandParameter = viewType };
        }

        private Image CreateIcon(string icon)
        {
            string img = $"pack://siteoforigin:,,,/Assets/Images/{icon}";
            return new Image
            {
                Margin = new System.Windows.Thickness(-2),
                Source = new BitmapImage(new Uri(img)),
            };
        }
    }
}
